<template>
  <div class="container fade-in">
    <!-- 页面头部 -->
    <div class="header">
      <div class="breadcrumb">
        <router-link to="/coupon-packages" class="breadcrumb-link">优惠券包管理</router-link>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-current">优惠券包详情</span>
      </div>
      <div class="actions">
        <router-link 
          :to="`/coupon-packages/edit/${packageId}`" 
          class="btn primary"
        >
          <span class="icon" v-html="'✏️'"></span>
          编辑
        </router-link>
        <button class="btn danger" @click="confirmDelete">
          <span class="icon" v-html="'🗑️'"></span>
          删除
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="!packageDetail" class="error-state">
      <div class="error-icon" v-html="'❌'"></div>
      <h3>优惠券包不存在</h3>
      <p>请检查链接是否正确，或者该优惠券包已被删除</p>
      <router-link to="/coupon-packages" class="btn primary">返回列表</router-link>
    </div>

    <div v-else class="content">
      <!-- 基本信息卡片 -->
      <div class="card slide-up" style="animation-delay: 0.1s">
        <div class="card-header">
          <h3>基本信息</h3>
          <div class="package-status">
            <span :class="['status-badge', packageDetail.isActive ? 'active' : 'inactive']">
              {{ packageDetail.isActive ? '启用' : '禁用' }}
            </span>
          </div>
        </div>
        <div class="card-content">
          <div class="info-grid">
            <div class="info-item">
              <label>优惠券包名称</label>
              <div class="value">{{ packageDetail.name }}</div>
            </div>
            <div class="info-item">
              <label>优惠券包ID</label>
              <div class="value">{{ packageDetail.id }}</div>
            </div>
            <div class="info-item">
              <label>创建时间</label>
              <div class="value">{{ formatDateTime(packageDetail.createdAt) }}</div>
            </div>
            <div class="info-item">
              <label>更新时间</label>
              <div class="value">{{ formatDateTime(packageDetail.updatedAt) }}</div>
            </div>
            <div class="info-item full-width">
              <label>描述</label>
              <div class="value">{{ packageDetail.description || '暂无描述' }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计信息卡片 -->
      <div class="card slide-up" style="animation-delay: 0.2s">
        <div class="card-header">
          <h3>统计信息</h3>
        </div>
        <div class="card-content">
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon" style="background: var(--primary)">🎟️</div>
              <div class="stat-info">
                <div class="stat-label">包含优惠券</div>
                <div class="stat-value">{{ packageDetail.couponCount || 0 }} 张</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon" style="background: var(--success)">📤</div>
              <div class="stat-info">
                <div class="stat-label">已领取次数</div>
                <div class="stat-value">{{ packageDetail.receiveCount || 0 }} 次</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon" style="background: var(--info)">⏰</div>
              <div class="stat-info">
                <div class="stat-label">有效期</div>
                <div class="stat-value">{{ packageDetail.validityPeriod || '永久' }} {{ packageDetail.validityPeriod ? '天' : '' }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 包含的优惠券模板 -->
      <div class="card slide-up" style="animation-delay: 0.3s">
        <div class="card-header">
          <h3>包含的优惠券模板</h3>
          <div class="card-actions">
            <button class="btn secondary sm" @click="loadCouponTemplates">
              <span class="icon">🔄</span>
              刷新
            </button>
          </div>
        </div>
        <div class="card-content">
          <div v-if="templatesLoading" class="loading-state">
            <div class="spinner"></div>
            <p>加载优惠券模板中...</p>
          </div>
          
          <div v-else-if="couponTemplates.length === 0" class="empty-state">
            <div class="empty-icon">🎟️</div>
            <h4>暂无优惠券模板</h4>
            <p>该优惠券包还没有包含任何优惠券模板</p>
          </div>
          
          <div v-else class="templates-grid">
            <div v-for="template in couponTemplates" :key="template.id" class="template-card">
              <div class="template-header">
                <h4>{{ template.name }}</h4>
                <div class="template-type">
                  <span :class="['type-badge', getCouponTypeClass(template.couponType)]">
                    {{ getCouponTypeText(template.couponType) }}
                  </span>
                </div>
              </div>
              
              <div class="template-content">
                <div class="template-info">
                  <div class="info-row">
                    <span class="label">优惠金额：</span>
                    <span class="value">{{ formatCouponValue(template) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">使用门槛：</span>
                    <span class="value">{{ formatThreshold(template.useThresholdAmount) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">有效期：</span>
                    <span class="value">{{ formatValidityPeriod(template) }}</span>
                  </div>
                  <div class="info-row">
                    <span class="label">状态：</span>
                    <span :class="['status', template.isActive ? 'active' : 'inactive']">
                      {{ template.isActive ? '启用' : '禁用' }}
                    </span>
                  </div>
                </div>
              </div>
              
              <div class="template-actions">
                <router-link 
                  :to="`/coupons/detail/${template.id}`" 
                  class="btn secondary sm"
                >
                  查看详情
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 领取记录 -->
      <div class="card slide-up" style="animation-delay: 0.4s">
        <div class="card-header">
          <h3>领取记录</h3>
          <div class="card-actions">
            <button class="btn secondary sm" @click="loadReceiveRecords">
              <span class="icon">🔄</span>
              刷新
            </button>
          </div>
        </div>
        <div class="card-content">
          <div v-if="recordsLoading" class="loading-state">
            <div class="spinner"></div>
            <p>加载领取记录中...</p>
          </div>
          
          <div v-else-if="receiveRecords.length === 0" class="empty-state">
            <div class="empty-icon">📝</div>
            <h4>暂无领取记录</h4>
            <p>该优惠券包还没有被任何用户领取</p>
          </div>
          
          <div v-else>
            <div class="table-container">
              <div v-if="recordsUnavailable" class="info-msg">
                领取记录接口未提供，列表暂不可用。
              </div>
              <div v-else-if="!recordsLoading && receiveRecords.length === 0" class="info-msg">
                暂无领取记录。
              </div>
              <template v-else>
              <table class="data-table">
                <thead>
                  <tr>
                    <th>用户ID</th>
                    <th>领取渠道</th>
                    <th>领取码</th>
                    <th>领取时间</th>
                    <th>IP地址</th>
                    <th>设备信息</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="record in receiveRecords" :key="record.id">
                    <td>{{ record.userId || '-' }}</td>
                    <td>{{ record.receiveChannel ?? '-' }}</td>
                    <td>{{ record.receiveCode || '-' }}</td>
                    <td>{{ formatDateTime(record.receivedAt) }}</td>
                    <td>{{ record.ipaddress || '-' }}</td>
                    <td>{{ record.deviceInfo || '-' }}</td>
                  </tr>
                </tbody>
              </table>
              </template>
            </div>
            
            <!-- 分页 -->
            <div v-if="receiveRecords.length > 0 && !recordsUnavailable" class="pagination">
              <button 
                class="btn secondary sm" 
                :disabled="recordsPagination.pageIndex <= 1"
                @click="changeRecordsPage(recordsPagination.pageIndex - 1)"
              >
                上一页
              </button>
              <span class="page-info">
                第 {{ recordsPagination.pageIndex }} 页，共 {{ Math.ceil(recordsPagination.totalCount / recordsPagination.pageSize) }} 页
              </span>
              <button 
                class="btn secondary sm" 
                :disabled="recordsPagination.pageIndex >= Math.ceil(recordsPagination.totalCount / recordsPagination.pageSize)"
                @click="changeRecordsPage(recordsPagination.pageIndex + 1)"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content" @click.stop>
        <h3>确认删除</h3>
        <p>确定要删除优惠券包 "{{ packageDetail?.name }}" 吗？此操作不可恢复。</p>
        <div class="modal-actions">
          <button class="btn secondary" @click="closeDeleteModal">取消</button>
          <button class="btn danger" @click="deletePackage">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  CouponService, 
  type CouponPackage, 
  type CouponTemplate,
  type CouponPackageReceiveRecord,
  getCouponTypeText,
  formatCouponAmount,
  formatCouponDiscount
} from '../services/coupon'
import { isSuccess } from '../services/types'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const templatesLoading = ref(false)
const recordsLoading = ref(false)
const recordsUnavailable = ref(false)
const showDeleteModal = ref(false)
const packageDetail = ref<CouponPackage | null>(null)
const couponTemplates = ref<CouponTemplate[]>([])
const receiveRecords = ref<CouponPackageReceiveRecord[]>([])

// 分页信息
const recordsPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

// 计算属性
const packageId = computed(() => route.params.id as string)

// 加载优惠券包详情
async function loadPackageDetail() {
  try {
    loading.value = true
    
  const result = await CouponService.getPackage(packageId.value)
    
    if (isSuccess(result) && result.data) {
      packageDetail.value = result.data
      // 加载相关数据
      await Promise.all([
        loadCouponTemplates(),
        loadReceiveRecords()
      ])
    } else {
      console.error('加载优惠券包详情失败:', result.message)
      packageDetail.value = null
    }
  } catch (error) {
    console.error('加载优惠券包详情出错:', error)
    packageDetail.value = null
  } finally {
    loading.value = false
  }
}

// 加载优惠券模板
async function loadCouponTemplates() {
  if (!packageDetail.value?.couponTemplateIds?.length) {
    couponTemplates.value = []
    return
  }
  
  try {
    templatesLoading.value = true
    
    // 这里需要根据模板ID列表获取模板详情
    // 由于当前API可能不支持批量获取，我们可以逐个获取或者调用列表接口
    const templates: CouponTemplate[] = []
    
    for (const templateId of packageDetail.value.couponTemplateIds) {
      try {
        const result = await CouponService.getTemplateDetail(templateId)
        if (isSuccess(result) && result.data) {
          templates.push(result.data)
        }
      } catch (error) {
        console.error(`获取模板 ${templateId} 详情失败:`, error)
      }
    }
    
    couponTemplates.value = templates
  } catch (error) {
    console.error('加载优惠券模板出错:', error)
    couponTemplates.value = []
  } finally {
    templatesLoading.value = false
  }
}

// 加载领取记录
async function loadReceiveRecords() {
  try {
    recordsLoading.value = true
    recordsUnavailable.value = false
    const result = await CouponService.getPackageReceiveRecords({
      packageId: packageId.value,
      pageIndex: recordsPagination.pageIndex,
      pageSize: recordsPagination.pageSize
    })
    if (isSuccess(result) && result.data) {
      receiveRecords.value = result.data.data
      recordsPagination.totalCount = result.data.total
    } else {
      receiveRecords.value = []
      recordsPagination.totalCount = 0
    }
    
  } catch (error) {
    console.error('加载领取记录出错:', error)
    // 后端未提供接口时（404），做友好降级处理
    if ((error as any)?.response?.status === 404) {
      recordsUnavailable.value = true
    }
    receiveRecords.value = []
  } finally {
    recordsLoading.value = false
  }
}

// 切换领取记录页面
function changeRecordsPage(page: number) {
  recordsPagination.pageIndex = page
  loadReceiveRecords()
}

// 确认删除
function confirmDelete() {
  showDeleteModal.value = true
}

// 关闭删除弹窗
function closeDeleteModal() {
  showDeleteModal.value = false
}

// 删除优惠券包
async function deletePackage() {
  if (!packageDetail.value?.id) return
  
  try {
  const result = await CouponService.deletePackage(packageDetail.value.id)
    
    if (isSuccess(result)) {
      // 删除成功，返回列表页
      router.push('/coupon-packages')
    } else {
      alert('删除失败：' + result.message)
    }
  } catch (error) {
    console.error('删除优惠券包出错:', error)
    alert('删除失败，请稍后重试')
  } finally {
    closeDeleteModal()
  }
}

// 格式化日期时间
function formatDateTime(dateStr?: string): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 格式化优惠券价值
function formatCouponValue(template: CouponTemplate): string {
  if (template.couponType === 1) { // 减免券
    return formatCouponAmount(template.discountAmount || 0)
  } else if (template.couponType === 2) { // 折扣券
    return formatCouponDiscount(template.discount || 0)
  }
  return '-'
}

// 格式化使用门槛
function formatThreshold(amount?: number): string {
  if (!amount || amount === 0) return '无门槛'
  return `满${formatCouponAmount(amount)}`
}

// 格式化有效期
function formatValidityPeriod(template: CouponTemplate): string {
  if (template.validityType === 1) {
    // 固定时间范围
    if (template.validityStartTime && template.validityEndTime) {
      const start = new Date(template.validityStartTime).toLocaleDateString('zh-CN')
      const end = new Date(template.validityEndTime).toLocaleDateString('zh-CN')
      return `${start} - ${end}`
    }
  } else if (template.validityType === 2) {
    // 领取后N小时内可用
    if (template.validityDuration) {
      const days = Math.floor(template.validityDuration / 24)
      const hours = template.validityDuration % 24
      if (days > 0) {
        return `领取后${days}天${hours > 0 ? hours + '小时' : ''}内可用`
      } else {
        return `领取后${hours}小时内可用`
      }
    }
  }
  return '-'
}

// 获取优惠券类型样式类
function getCouponTypeClass(type: number): string {
  switch (type) {
    case 1: return 'reduction'
    case 2: return 'discount'
    case 3: return 'gift'
    default: return 'default'
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadPackageDetail()
})
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.breadcrumb-link {
  color: var(--primary);
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  color: var(--text-secondary);
}

.breadcrumb-current {
  color: var(--text-primary);
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover {
  background: var(--primary-dark);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--bg-tertiary);
}

.btn.danger {
  background: var(--danger);
  color: white;
}

.btn.danger:hover {
  background: var(--danger-dark);
}

.btn.sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-state, .error-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border);
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.package-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: var(--success-light);
  color: var(--success);
}

.status-badge.inactive {
  background: var(--warning-light);
  color: var(--warning);
}

.status-badge.success {
  background: var(--success-light);
  color: var(--success);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
}

.info-item .value {
  font-size: 16px;
  color: var(--text-primary);
  word-break: break-all;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.template-card {
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  background: var(--bg-secondary);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.template-header h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  flex: 1;
}

.template-type {
  margin-left: 12px;
}

.type-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.type-badge.reduction {
  background: var(--success-light);
  color: var(--success);
}

.type-badge.discount {
  background: var(--info-light);
  color: var(--info);
}

.type-badge.gift {
  background: var(--warning-light);
  color: var(--warning);
}

.type-badge.default {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

.template-content {
  margin-bottom: 16px;
}

.template-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.info-row .label {
  color: var(--text-secondary);
}

.info-row .value {
  color: var(--text-primary);
  font-weight: 500;
}

.info-row .status.active {
  color: var(--success);
}

.info-row .status.inactive {
  color: var(--warning);
}

.template-actions {
  display: flex;
  gap: 8px;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 16px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border);
}

.data-table th {
  background: var(--bg-secondary);
  font-weight: 600;
  color: var(--text-primary);
}

.data-table td {
  color: var(--text-secondary);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  max-width: 400px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: var(--text-primary);
}

.modal-content p {
  margin: 0 0 24px 0;
  color: var(--text-secondary);
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.slide-up {
  animation: slideUp 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .templates-grid {
    grid-template-columns: 1fr;
  }
  
  .template-header {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  .template-type {
    margin-left: 0;
    align-self: flex-start;
  }
}
</style>
